// 将axios库绑定到axios变量
import axios from "axios";
// 引入Element Plus的消息提示
import { ElMessage } from 'element-plus'
// 声明基础url
const requestUrl = "http://localhost:8080";
// 创建一个axios实例
const axiosInstance = axios.create({
    baseURL: requestUrl
})
//请求拦截器,在请求前执行
axiosInstance.interceptors.request.use((config) => {
    if (localStorage.getItem('sysuser') as string !== null){
         //每次请求添加Authorization到请求头中
        config.headers.Authorization = JSON.parse(localStorage.getItem('sysuser') as string).jwt
        return config;
    }
    return config;
},
    (error) => {
        return Promise.reject(error)
    }
)
//请求拦截器,在请求后执行
axiosInstance.interceptors.response.use(
    // 获取响应结果
    (res) => {
        // 这里多返回一层data,方便操作
        return res.data
    },
    // error的集中处理
    (error) => {
        console.log(error)
        const status: number = error.response.status
        switch (status) {
            case 404:
                console.error("接口不存在或者请求方式不对");
                break;
            case 401:
                console.error("没有权限访问");
                break;
            case 500:
                ElMessage({ message: "服务器请求失败", duration: 1500 });
                break;
            case 400:
                ElMessage({ message: error.response.data.msg, duration: 1500 });
                break;
        }
        return Promise.reject(error)
    }
)
// 封装统一的返回数据类型,使用泛型T作为data的类型
export interface ApiResponse<T> {
    data: T;
    msg: string;
    code: number
}
// 封装get请求
export const get = <T>(url: string, params?: object): Promise<ApiResponse<T>> => {
    return axiosInstance.get(url, { params })
}
//封装post请求
export const post = <T>(url: string, data?: object): Promise<ApiResponse<T>> => {
    return axiosInstance.post(url, data)
}